package de.hach.manno.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.util.Log;

public class MannOWebservice {
	private static final String TAG = "MannOWebservice";

	// private String baseURL = "http://192.168.2.28/MannO/webservice.php/";
	// private String baseURL = "http://manno.hahnx.de/webservice.php/";
	private static final String baseURL = "http://manno.hahnx.de/webservice.php/";
	private static final String encoding = "ISO-8859-15";
	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public List<Club> getClubUpdates(Calendar lastUpdate) {
		try {
			URL url = new URL(baseURL + "clubUpdate/"
					+ URLEncoder.encode(sdf.format(lastUpdate.getTime())));
			Log.d(TAG, "Club Update URL: " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String source = "";
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				source += inputLine;
			}
			in.close();
			conn.disconnect();
			Serializer serializer = new Persister();
			ClubList clubList = serializer.read(ClubList.class, source);
			Log.d(TAG, "Found " + clubList.getClubs().size()
					+ " clubs to update");
			return clubList.getClubs();

		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			return null;
		}
	}

	public List<Event> getEventUpdates(Calendar lastUpdate) {
		try {
			URL url = new URL(baseURL + "eventUpdate/"
					+ URLEncoder.encode(sdf.format(lastUpdate.getTime())));
			Log.d(TAG, "Event Update URL: " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String source = "";
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				source += inputLine;
			}
			in.close();
			conn.disconnect();
			Serializer serializer = new Persister();
			EventList eventList = serializer.read(EventList.class, source);
			Log.d(TAG, "Found " + eventList.getEvents().size()
					+ " Events to update");
			return eventList.getEvents();

		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			return null;
		}
	}

	public List<Match> getMatchUpdates(Calendar lastUpdate) {
		try {
			URL url = new URL(baseURL + "matchUpdate/"
					+ URLEncoder.encode(sdf.format(lastUpdate.getTime())));
			Log.d(TAG, "Match Update URL: " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String source = "";
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				source += inputLine;
			}
			in.close();
			conn.disconnect();
			Serializer serializer = new Persister();
			MatchList matchList = serializer.read(MatchList.class, source);
			Log.d(TAG, "Found " + matchList.getMatches().size()
					+ " Matches to update");
			return matchList.getMatches();

		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			return null;
		}
	}

	public List<Player> getPlayerUpdates(Calendar lastUpdate) {
		try {
			URL url = new URL(baseURL + "playerUpdate/"
					+ URLEncoder.encode(sdf.format(lastUpdate.getTime())));
			Log.d(TAG, "Player Update URL: " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String source = "";
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				source += inputLine;
			}
			in.close();
			conn.disconnect();
			Serializer serializer = new Persister();
			PlayerList playerList = serializer.read(PlayerList.class, source);
			Log.d(TAG, "Found " + playerList.getPlayers().size()
					+ " Players to update");
			return playerList.getPlayers();

		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			return null;
		}
	}

	public List<PlaysFor> getPlaysForUpdates(Calendar lastUpdate) {
		try {
			URL url = new URL(baseURL + "playsForUpdate/"
					+ URLEncoder.encode(sdf.format(lastUpdate.getTime())));
			Log.d(TAG, "PlaysFor Update URL: " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String source = "";
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				source += inputLine;
			}
			in.close();
			conn.disconnect();
			Serializer serializer = new Persister();
			PlaysForList playsForList = serializer.read(PlaysForList.class,
					source);
			Log.d(TAG, "Found " + playsForList.getPlaysFors().size()
					+ " PlaysFors to update");
			return playsForList.getPlaysFors();

		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			return null;
		}
	}

	public boolean[] getStatus(Calendar now) {
		try {
			URL url = new URL(baseURL + "status");
			Log.d(TAG, "Status Update URL: " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String source = "";
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				source += inputLine;
			}
			in.close();
			conn.disconnect();
			Serializer serializer = new Persister();
			Status status = serializer.read(Status.class, source);
			Calendar cal = Calendar.getInstance();
			boolean[] updated = new boolean[5];
			cal.setTime(sdf.parse(status.getClub()));
			updated[0] = now.before(cal);
			cal.setTime(sdf.parse(status.getEvent()));
			updated[1] = now.before(cal);
			cal.setTime(sdf.parse(status.getMatch()));
			updated[2] = now.before(cal);
			cal.setTime(sdf.parse(status.getPlayer()));
			updated[3] = now.before(cal);
			cal.setTime(sdf.parse(status.getPlaysFor()));
			updated[4] = now.before(cal);
			return updated;
		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			return null;
		}
	}

	public static boolean putClub(Club club) {
		try {
			String s = baseURL + "put/club/" + club.getId() + "/"
					+ URLEncoder.encode(club.getName());
			URL url = new URL(s);
			Log.d(TAG, "post " + club + " to " + url.getPath());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("PUT");
			conn.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				Log.d(TAG, "PUT REQUEST:\t" + inputLine);
			}
			in.close();
			conn.disconnect();
			return true;
		} catch (MalformedURLException e) {
			Log.e(TAG, "MalformedURLException: " + e.getMessage());
			return false;
		} catch (IOException e) {
			Log.e(TAG, "IOException: " + e.getMessage());
			Log.e(TAG, e.toString());
			return false;
		}
	}
}
